package handler;

import com.alibaba.fastjson.JSONObject;
import dto.LinkDTO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * 基础信息获取
 *
 * @Author yuan
 * @Date 2021/6/26 15:24
 */
@Slf4j
public class BaseHandler {

    /**
     * 获取token
     *
     * @return
     */
    public static String getToken() {
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            Request request = new Request.Builder()
                    .url("http://api.qa.it.shanghai.nyu.edu/api/app/getToken?appKey=clk-test&appSecret=8BRjYoo6UWychyuykX")
                    .method("GET", null)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject obj = JSONObject.parseObject(response.body().string());
                return obj.get("result").toString();
            }
            return "";
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return "";
    }

    /**
     * 获取批量下载的链接
     *
     * @return
     */
    public static List<LinkDTO> getBatchDownloadLink() {
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            //MediaType mediaType = MediaType.parse("application/json");
            MediaType mediaType = MediaType.Companion.parse("application/json");
            RequestBody body=RequestBody.Companion.create("{\"fileIdList\":[84]}",mediaType);
            //RequestBody body = RequestBody.create(mediaType, "{\"fileIdList\":[84]}");
            Request request = new Request.Builder()
                    .url("http://api.qa.it.shanghai.nyu.edu/api/file/batchGetDownloadLink")
                    .post(body)
                    .addHeader("X-Access-Token", getToken())
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject obj = JSONObject.parseObject(response.body().string());
                if (obj.get("success").toString().toLowerCase() == "true") {
                    List<LinkDTO> list = JSONObject.parseArray(obj.get("result").toString(),
                            LinkDTO.class);
                    return list;
                }
            }
            return null;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 下载图片
     *
     * @return
     */
    public static void downLoadPhoto(List<LinkDTO> list) {
        try {
            String rootPath = "D:\\Java\\springboot-compose\\springboot-okhttp\\src\\main\\resources\\upload";
            for (LinkDTO linkDTO : list) {
                if ("ok".equalsIgnoreCase(linkDTO.message)) {
                    OkHttpClient client = new OkHttpClient().newBuilder()
                            .build();
                    Request request = new Request.Builder()
                            .url(linkDTO.getLink())
                            .method("GET", null)
                            .build();
                    Response response = client.newCall(request).execute();
                    byte[] buff = new byte[4096];
                    int len = 0;
                    File filePath = new File(rootPath);
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    File realPath = new File(rootPath + File.separator + linkDTO.getFileId() + ".jpg");
                    InputStream is = response.body().byteStream();
                    FileOutputStream fos = new FileOutputStream(realPath);
                    while ((len = is.read(buff)) != -1) {
                        fos.write(buff, 0, len);
                    }
                    fos.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 上传图片
     * C:\Users\yuan\Desktop
     *
     * @Author yuan
     * @Date 2021/6/26 18:39
     */
    public static void upload(String filePath) {
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file", filePath,
                            RequestBody.create(MediaType.parse("application/octet-stream"),
                                    new File(filePath)))
                    .addFormDataPart("description", "idcard.jpg")
                    .addFormDataPart("fileType", "DOCUMENT")
                    .addFormDataPart("accessControl", "PRIVATE")
                    .build();
            Request request = new Request.Builder()
                    .url("http://api.qa.it.shanghai.nyu.edu/api/file/upload")
                    .method("POST", body)
                    .addHeader("X-Access-Token", getToken())
                    .build();
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                JSONObject obj = JSONObject.parseObject(response.body().string());
                if (obj.get("success").toString().toLowerCase() == "true") {
                    JSONObject object= JSONObject.parseObject(obj.get("result").toString());
                    int fileId= (int) object.get("fileId");
                    System.out.println("fileId:"+fileId);

                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

}
